package com.jcode.netty.serialize;

import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.jcode.netty.exception.SerializationException;

/**
 * 
 * @Desc FastJson序列化
 *
 * @Author dreajay
 * @DateTime 2016年11月18日 上午10:33:28
 *
 */
public class FastJsonSerializer implements Serializer {
	private static SerializeConfig config = new SerializeConfig();
	public static final Charset CHARSET = Charset.forName("UTF-8");

	static {
		config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
	}

	@Override
	public SerializeType getType() {
		return SerializeType.JSON;
	}

	@Override
	public byte[] serialize(Serializable obj) throws SerializationException {
		String json = toJson(obj, false);
		return json.getBytes(CHARSET);
	}

	@Override
	public <T> T deserialize(byte[] data, Class<T> clazz) throws SerializationException {
		final String json = new String(data, CHARSET);
		return parseJson(json, clazz);
	}

	/**
	 * Java对象转换为Json字符串
	 * 
	 * @param object
	 * @return
	 */
	public static String toJson(Object object, SerializerFeature... features) {
		return JSON.toJSONString(object, config, features);
	}

	/**
	 * Java对象转换为Json字符串
	 * 
	 * @param object
	 * @return
	 */
	public static String toJson(Object object) {
		return JSON.toJSONString(object, config);
	}

	/**
	 * Java对象转换为Json字符串，并设置是否格式化
	 * 
	 * @param object
	 * @param prettyFormat
	 * @return
	 */
	public static String toJson(final Object object, boolean prettyFormat) {
		return JSON.toJSONString(object, prettyFormat);
	}

	/**
	 * 解析json字符串为Java对象
	 * 
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T parseJson(String json, Class<T> clazz) {
		return JSON.parseObject(json, clazz);
	}

}
